<template>
  <div>
    <h2>实时聊天</h2>
    <div class="chat-container">
      <div class="messages">
        <div v-for="(message, index) in messages" :key="index" :class="['message', message.sender === 'User' ? 'sent' : 'received']">
          {{ message.content }}
        </div>
      </div>
      <div class="input-container">
        <input v-model="newMessage" @keyup.enter="sendMessage" placeholder="输入消息并按 Enter 发送" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import SockJS from 'sockjs-client/dist/sockjs.js';
import Stomp from 'webstomp-client'; // 使用 webstomp-client

const messages = ref([]);
const newMessage = ref('');
let stompClient = null;

const wsUrl = 'http://124.223.56.87:8080/ws'; // 替换为你的 WebSocket 端点

const connectWebSocket = () => {
  const socket = new SockJS(wsUrl);
  stompClient = Stomp.over(socket);

  stompClient.connect({}, (frame) => {
    console.log('Connected: ' + frame);
    stompClient.subscribe('/topic/messages', (message) => {
      console.log(message);
      const messageObj = {
        sender: '',
        content: message.body,
      };
      messages.value.push(messageObj);
    });
  }, (error) => {
    console.error('Connection error: ' + error);
  });
};

const sendMessage = () => {
  if (stompClient && newMessage.value.trim() !== '') {
    const messageObj = {
      sender: 'User',
      content: newMessage.value,
    };
    stompClient.send('/app/Chat', newMessage.value, {});
    messages.value.push(messageObj);
    newMessage.value = '';
  }
};

onMounted(() => {
  connectWebSocket();
});

onUnmounted(() => {
  if (stompClient) {
    stompClient.disconnect(() => console.log('Disconnected'));
  }
});
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 400px;
  border: 1px solid #ccc;
  padding: 10px;
}

.messages {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.message {
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 5px;
  max-width: 70%;
  word-wrap: break-word;
}

.sent {
  background-color: #d1ffd1;
  align-self: flex-end;
  text-align: right;
}

.received {
  background-color: #f1f1f1;
  align-self: flex-start;
  text-align: left;
}

.input-container {
  display: flex;
}

input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>
